package com.uniview.service.orderType.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.uniview.entity.vo.Pager;
import com.uniview.entity.vo.orderType.ExternalTest;
import com.uniview.plugins.adapter.OLDataSource;
import com.uniview.service.orderType.ExternalTestService;

@Service("externalTestService")
public class ExternalTestServiceImpl implements ExternalTestService {
	
	private Logger logger = Logger.getLogger(ExternalTestServiceImpl.class);
	
	@Value("#{configProperties['uniview.ExternalTest']}")
	private String externalTestTable; 
	
	@Value("#{configProperties['uniview.ExternalTestRole']}")
	private String externalTestRoleTable;
	
	@Autowired
	private OLDataSource olDataSource;
	
	@Override
	public boolean checkSuperRoleByWorkNo(String workNo) throws Exception {
		// TODO Auto-generated method stub
		if (StringUtils.isNotBlank(workNo)) {
			if (workNo.length() > 5) {
				workNo = workNo.substring(workNo.length() - 5, workNo.length());
				String countSql = "select count(1) from " + externalTestRoleTable + " where INSTR(\"Member\", " + workNo + ") > 0";
				int total = olDataSource.getCount(countSql.toString());
				return total > 0;
			}
		}
		return false;
	}

	@Override
	public Pager<ExternalTest> findExternalTestByWorkNo(String workNo,String queryString, int page, int limit) throws Exception{
		//处理域账号
		workNo = workNo.substring(1, workNo.length());
		StringBuilder builder = new StringBuilder();
		builder.append("select * from (select A.*,ROWNUM as id FROM ( ");
		builder.append("select * from " + this.externalTestTable +" where INSTR(\"WF_AddName\","+workNo+") >0 ");
		if(StringUtils.isNotBlank(queryString)){
			builder.append(" and (\"xiangmumc\" like '%"+queryString+"%' or \"kehumc\" like '%"+queryString+"%')");
		}
		builder.append(" ) A WHERE ROWNUM <= " + page + " * " + limit + " ) WHERE id > (" + page + " - 1) *" + limit);
		
		logger.debug("查询用户对外测试数据sql========" + builder.toString());
		List<ExternalTest> list = olDataSource.queryForList(ExternalTest.class, builder.toString());
		//查询总记录数
		String countSql = "select count(*) from " +externalTestTable+ " where INSTR(\"WF_AddName\","+workNo+") >0 ";
		if(StringUtils.isNotBlank(queryString)){
			countSql += " and (\"xiangmumc\" like '%"+queryString+"%' or \"kehumc\" like '%"+queryString+"%')";
		}
		logger.debug("统计用户对外测试数据sql========" + countSql.toString());
		int total = olDataSource.getCount(countSql.toString());
		Pager<ExternalTest> pager = new Pager<ExternalTest>();
		
		pager.setPagerList(list);
		pager.setTotalRow(total);
		return pager;
	}

}
